﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

namespace CrmContrib.Workflow.Activities.Opportunities
{
    [CrmWorkflowActivity( "Close opportunity as won", "CrmContrib \\ Opportunities" )]
    public class CloseOpportunityAsWonActivity : Activity
    {
        private ICrmService _CrmService;

        [CrmInput( "Opportunity" )]
        [CrmReferenceTarget("opportunity")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup Opportunity
        {
            get { return (Lookup)base.GetValue( OpportunityProperty ); }
            set { base.SetValue( OpportunityProperty, value ); }
        }

        public static readonly DependencyProperty OpportunityProperty = DependencyProperty.Register( "Opportunity", typeof( Lookup ), typeof( CloseOpportunityAsWonActivity ) );

        [CrmInput( "Actual revenue" )]
        [ValidationOption( ValidationOption.Required )]
        public CrmMoney ActualRevenue
        {
            get { return (CrmMoney)base.GetValue( ActualRevenueProperty ); }
            set { base.SetValue( ActualRevenueProperty, value ); }
        }

        public static readonly DependencyProperty ActualRevenueProperty = DependencyProperty.Register( "ActualRevenue", typeof( CrmMoney ), typeof( CloseOpportunityAsWonActivity ) );

        protected override ActivityExecutionStatus Execute( ActivityExecutionContext executionContext )
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            _CrmService = workflowContext.CreateCrmService();

            var close = new opportunityclose { opportunityid = Opportunity, actualrevenue = ActualRevenue, actualend = new CrmDateTime( DateTime.Now.ToString( "u" ) ) };
            var markAsWonRequest = new WinOpportunityRequest { OpportunityClose = close, Status = -1 };

            _CrmService.Execute( markAsWonRequest );

            return base.Execute( executionContext );
        }
    }
}
